package org.zbclan.bf2.rcon.service;

import java.io.Serializable;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zbclan.bf2.rcon.model.LocalProfile;

/**
 * @author renfeng
 * 
 */
public class PersistenceServiceImpl implements PersistenceService, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8752526980345359482L;

	private static final Logger logger = LoggerFactory
			.getLogger(PersistenceServiceImpl.class);

	private static final PersistenceManagerFactory pmf = JDOHelper
			.getPersistenceManagerFactory("datanucleus.properties");

	public <PC> PC save(PC pc) {

		PersistenceManager pm = pmf.getPersistenceManager();
		Transaction tx = pm.currentTransaction();
		try {

			tx.begin();

			pc = pm.makePersistent(pc);

			tx.commit();
		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			pm.close();
		}

		return pc;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public <PC> int compare(PC pc1, PC pc2) {

		PersistenceManager pm = pmf.getPersistenceManager();

		Comparable id1 = (Comparable) pm.getObjectId(pc1);
		Comparable id2 = (Comparable) pm.getObjectId(pc2);

		return id1.compareTo(id2);
	}

	@Override
	public LocalProfile findLocalProfileByGamespyNick(String gamespyNick) {

		LocalProfile result;

		PersistenceManager pm = pmf.getPersistenceManager();
		Transaction tx = pm.currentTransaction();
		try {

			tx.begin();

			Query q = pm.newNamedQuery(LocalProfile.class,
					"findLocalProfileByGamespyNick");
			result = (LocalProfile) q.executeWithArray(gamespyNick);

			tx.commit();
		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			pm.close();
		}

		return result;
	}
}
